package com.neteast.androidclient.contact.widget;

import java.util.ArrayList;
import com.neteast.androidclient.contact.R;
import com.neteast.androidclient.contact.domain.ContactData;
import com.neteast.androidclient.contact.util.ValidateUtil;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class ContactContainer extends LinearLayout implements View.OnClickListener {
	
	private LayoutInflater inflater;
	private Activity context;
	/**容器的内容，1是电话，2是邮箱，3是im，4是地址*/
	private int type;
	/**可编辑条目当前标签的序列*/
	private int index=0;
	/**可编辑条目的标签*/
	private String[] labels;
	/**标签*/
	private TextView tvLabel;
	/**自定义标签*/
	private EditText etCustomLabel;
	/**标签的列表项*/
	private ListView listSelect;
	/**自定义标签窗口*/
	private PopupWindow winCustomLabel;
	/**选择标签窗口*/
	private PopupWindow winSelectLabel;
	
	/**
	 * Context必须是Activity
	 * @param context
	 */
	public ContactContainer(Context context) {
		super(context);
	}
	/**
	 * Context必须是Activity
	 * @param context
	 */
	public ContactContainer(Context context,AttributeSet set) {
		super(context, set);
		this.context=(Activity) context;
		inflater = LayoutInflater.from(context);
		TypedArray ta = context.obtainStyledAttributes(set,R.styleable.containerType);
		type = ta.getInteger(R.styleable.containerType_type, 1);
		ta.recycle();
		initLabels();
		createPopWindow();
	}
	
	/**
	 * 根据type不同，初始化选择标签的内容
	 */
	private void initLabels() {
		switch (type) {
		case 1:
			labels=context.getResources().getStringArray(R.array.phone_types);
			break;
		case 2:
			labels=context.getResources().getStringArray(R.array.email_types);
			break;
		case 3:
			labels=context.getResources().getStringArray(R.array.im_types);
			break;
		case 4:
			labels=context.getResources().getStringArray(R.array.location_types);
			break;
		}
	}
	/**
	 * 创建泡泡窗口，选择标签窗口和自定义标签窗口
	 */
	private void createPopWindow() {
		//构建选择标签窗口
    	LinearLayout selectDialogLayout = (LinearLayout) inflater.inflate(R.layout.dialog_list_view, null);
    	TextView title = (TextView) selectDialogLayout.findViewById(R.id.title);
    	title.setText("请选择标签");
    	listSelect = (ListView) selectDialogLayout.findViewById(R.id.list);
    	listSelect.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
				String value=labels[position];
				if (value.indexOf("自定义")!=-1) {
					winSelectLabel.dismiss();
					winCustomLabel.showAtLocation(context.getWindow().getDecorView(), Gravity.CENTER, 0, 0);
					return;
				}
				tvLabel.setText(value);
				winSelectLabel.dismiss();
			}
		});
    	listSelect.setAdapter(new ArrayAdapter<String>(context, R.layout.list_item_text, labels));
    	winSelectLabel = new PopupWindow(selectDialogLayout, 300, 450);
    	winSelectLabel.setBackgroundDrawable(getResources().getDrawable(android.R.color.transparent));
    	winSelectLabel.setFocusable(true);
    	//构建自定义标签窗口
    	View root = inflater.inflate(R.layout.dialog_custom_label, null);
    	etCustomLabel = (EditText) root.findViewById(R.id.custom_label);
    	root.findViewById(R.id.btn_OK).setOnClickListener(this);
    	root.findViewById(R.id.btn_cancel).setOnClickListener(this);
    	winCustomLabel = new PopupWindow(root, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    	winCustomLabel.setFocusable(true);
    	winCustomLabel.setBackgroundDrawable(getResources().getDrawable(android.R.color.transparent));
	}
	/**
	 * 加入空白的可编辑条目
	 */
	public void addItem(){
		addItem(null);
	}
	/**
	 * 加入可编辑条目，并且用ContactData填充
	 * @param data
	 */
	public void addItem(ContactData data){
		View item = inflater.inflate(R.layout.item_contact_edit, null);
		item.setMinimumHeight(48);
		EditText contentET = (EditText) item.findViewById(R.id.item_content);
		tvLabel = (TextView) item.findViewById(R.id.item_label);
		if (index==labels.length-1) {
			index=0;
		}
		tvLabel.setText(labels[index++]);
		tvLabel.setOnClickListener(this);
		item.findViewById(R.id.item_delitem).setOnClickListener(this);
		switch (type) {
		case 1:
			contentET.setHint("请输入电话");
			contentET.setInputType(EditorInfo.TYPE_CLASS_PHONE);
			break;
		case 2:
			contentET.setHint("请输入邮箱");
			contentET.setInputType(EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS|EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE);
			break;
		case 3:
			contentET.setHint("请输入IM号");
			contentET.setInputType(EditorInfo.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT|EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE);
			break;
		case 4:
			contentET.setHint("请输入地址");
			contentET.setInputType(EditorInfo.TYPE_CLASS_TEXT|EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE);
			break;
		}
		LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
		params.bottomMargin=13;
		
		if (data!=null) {
			tvLabel.setText(data.label);
			contentET.setText(data.content);
		}
		addView(item, params);
	}
	/**
	 * 当编辑联系人完成时调用
	 * 	会从容器里将所有的子条目取出，根据他们的内容进行合法性验证，然后组拼成ContactData返回
	 * @param datas
	 * @return
	 */
	public boolean onDone(ArrayList<ContactData> datas){
		int count = this.getChildCount();
		ContactData data=null;
		for (int i = 0; i < count; i++) {
			LinearLayout ll = (LinearLayout) this.getChildAt(i);
			TextView tvLabel=(TextView) ll.findViewById(R.id.item_label);
			EditText etContent=(EditText) ll.findViewById(R.id.item_content);
			String label=tvLabel.getText().toString().trim();
			String content=etContent.getText().toString().trim();
			if (TextUtils.isEmpty(content)) {
				continue;
			}
			if (label.indexOf("手机")!=-1) {
				content=ValidateUtil.formatMobilePhone(content);
			}
			if (!ValidateUtil.validate(type,label,content)) {
				etContent.requestFocus();
				Toast.makeText(context, label+"格式错误！", 300).show();
				return false;
			}
			data=new ContactData();
			data.label=label;
			data.content=content;
			data.mimeTypeId=type;
			datas.add(data);
		}
		data=null;
		return true;
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.item_label:
			tvLabel=(TextView) v;
			winSelectLabel.showAtLocation(context.getWindow().getDecorView(),Gravity.CENTER,0,0);
			break;
		case R.id.item_delitem:
			ContactContainer.this.removeView((View)v.getParent());
			break;
		case R.id.btn_OK:
			String value = etCustomLabel.getText().toString();
			if (TextUtils.isEmpty(value)) {
				Toast.makeText(context, "标签不能为空", 300).show();
				return;
			}
			tvLabel.setText(value);
			winCustomLabel.dismiss();
			break;
		case R.id.btn_cancel:
			winCustomLabel.dismiss();
			break;
		}
	}
}
